using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Subscriptions
{
    [Serializable()]
    public class Subscription : Csla.BusinessBase<Subscription>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _subscriptionid = Guid.NewGuid();
        private Guid _userid = Guid.Empty;
        private Guid _itemid = Guid.Empty;
        private bool _notify = false;
        private bool _archived = false;
        private Boolean _HasData = false;
        private int _ivSubscriptionType = 0;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Subscriptionid
        {
            get
            {
                CanReadProperty("Subscriptionid", true);
                return _subscriptionid;
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        public Guid itemid
        {
            get
            {
                CanReadProperty("itemid", true);
                return _itemid;
            }
            set
            {
                CanWriteProperty("itemid", true);
                if (!_itemid.Equals(value))
                {
                    _itemid = value;
                    PropertyHasChanged("itemid");
                }
            }
        }

        public bool Notify
        {
            get
            {
                CanReadProperty("Notify", true);
                return _notify;
            }
            set
            {
                CanWriteProperty("Notify", true);
                if (!_notify.Equals(value))
                {
                    _notify = value;
                    PropertyHasChanged("Notify");
                }
            }
        }

        public bool Archived
        {
            get
            {
                CanReadProperty("Archived", true);
                return _archived;
            }
            set
            {
                CanWriteProperty("Archived", true);
                if (!_archived.Equals(value))
                {
                    _archived = value;
                    PropertyHasChanged("Archived");
                }
            }
        }

        public Boolean HasData
        {
            get
            {
                return _HasData;
            }
            set
            {
                _HasData = value;
                //if (value != null)
                //{
                //    _HasData = value;
                //}
                //else
                //{
                //    _HasData = false;
                //}
            }
        }

        public int ivSubscriptionType
        {
            get
            {
                CanReadProperty("ivSubscriptionType", true);
                return _ivSubscriptionType;
            }
            set
            {
                CanWriteProperty("ivSubscriptionType", true);
                if (!_ivSubscriptionType.Equals(value))
                {
                    _ivSubscriptionType = value;
                    PropertyHasChanged("ivSubscriptionType");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _subscriptionid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {

        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Subscription
            //AuthorizationRules.AllowRead("Subscriptionid", "SubscriptionReadGroup");
            //AuthorizationRules.AllowRead("Userid", "SubscriptionReadGroup");
            //AuthorizationRules.AllowRead("itemid", "SubscriptionReadGroup");
            //AuthorizationRules.AllowRead("Notify", "SubscriptionReadGroup");
            //AuthorizationRules.AllowRead("Archived", "SubscriptionReadGroup");

            //AuthorizationRules.AllowWrite("Userid", "SubscriptionWriteGroup");
            //AuthorizationRules.AllowWrite("itemid", "SubscriptionWriteGroup");
            //AuthorizationRules.AllowWrite("Notify", "SubscriptionWriteGroup");
            //AuthorizationRules.AllowWrite("Archived", "SubscriptionWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Subscription
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SubscriptionViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Subscription
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SubscriptionAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Subscription
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SubscriptionEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Subscription
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("SubscriptionDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Subscription()
        { /* require use of factory method */
        }

        public static Subscription NewSubscription()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Subscription");
            return DataPortal.Create<Subscription>();
        }

        public static Subscription GetSubscription(Guid subscriptionid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Subscription");
            return DataPortal.Fetch<Subscription>(new Criteria(subscriptionid));
        }

        public static Subscription GetSubscription(Guid itemid, Guid UserID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Subscription");
            return DataPortal.Fetch<Subscription>(new Criteria(itemid, UserID));
        }

        public static void DeleteSubscription(Guid subscriptionid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Subscription");
            DataPortal.Delete(new Criteria(subscriptionid));
        }

        public override Subscription Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Subscription");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Subscription");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Subscription");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Subscriptionid;
            public Guid itemid;
            public Guid UserID;

            public Criteria(Guid subscriptionid)
            {
                this.Subscriptionid = subscriptionid;
            }

            public Criteria(Guid itemid, Guid UserID)
            {
                this.itemid = itemid;
                this.UserID = UserID;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@itemid", criteria.itemid);
            DAL.AddParameter("@userid", criteria.UserID);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetSubscriptionsByUserID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            while (dr.Read())
            {
                _subscriptionid = dr.GetGuid("subscriptionid");
                _userid = dr.GetGuid("userid");
                _itemid = dr.GetGuid("itemid");
                _notify = dr.GetBoolean("notify");
                _archived = dr.GetBoolean("archived");
                _ivSubscriptionType = dr.GetInt32("iv_subscriptiontype");

                _HasData = true;
            }
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertSubscriptions.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@subscriptionid", _subscriptionid);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@itemid", _itemid);
            DAL.AddParameter("@ivsubscriptiontype", _ivSubscriptionType);

            if (_notify != false)
                DAL.AddParameter("@notify", _notify);
            else
                DAL.AddParameter("@notify", 0);
            if (_archived != false)
                DAL.AddParameter("@archived", _archived);
            else
                DAL.AddParameter("@archived", 0);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateSubscriptions.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@subscriptionid", _subscriptionid);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@itemid", _itemid);
            DAL.AddParameter("@ivsubscriptiontype", _ivSubscriptionType);

            if (_notify != false)
                DAL.AddParameter("@notify", _notify);
            else
                DAL.AddParameter("@notify", 0);
            if (_archived != false)
                DAL.AddParameter("@archived", _archived);
            else
                DAL.AddParameter("@archived", 0);
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_subscriptionid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@subscriptionid", criteria.Subscriptionid);

            DAL.ExecuteNonQuery(Procs.DeleteSubscriptions.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
